package com.memoir.jpa.service;

import com.memoir.jpa.model.TodoDto;
import com.memoir.jpa.repository.TodoPagingAndSortingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ldm
 * @since 2017-09-14
 */
@Service
public class TodoPagingAndSortingService {

    @Autowired
    private TodoPagingAndSortingRepository todoRepository;

    public List<TodoDto> findAllBySort(){

        //createTime指定的是类的成员变量
        Sort.Order createTime = new Sort.Order(Sort.Direction.DESC, "createTime", Sort.NullHandling.NULLS_FIRST);
        return (List<TodoDto>) todoRepository.findAll(new Sort(createTime));
    }


    /**
     * jpa利用pageable实现分页，pageable通过计算会发出两条sql语句，
     * 1条是是类似select * from tableName limit pageNum,pageSize,
     * 另1条是计算总条数select count(*) from tableName
     */
    public List<TodoDto> findAllByPage(int pageNum){

        int size = 10;  //默认10条

        Sort.Order createTime = new Sort.Order(Sort.Direction.DESC, "createTime", Sort.NullHandling.NULLS_FIRST);   //null值排前
        Sort.Order title = new Sort.Order(Sort.Direction.ASC, "title", Sort.NullHandling.NULLS_FIRST);  //null值排前
        Pageable pageable = new PageRequest(pageNum-1,size,new Sort(title,createTime));

        //上面的sort和order 可以用qsort和orderspecifier来表示
        //new QSort();
        //OrderSpecifier
        Page<TodoDto> todoDtoPage = todoRepository.findAll(pageable);

        long totalSize = todoDtoPage.getTotalElements();    //总条数
        int totalPages = todoDtoPage.getTotalPages();       //总页数

        return todoDtoPage.getContent();    //转化为list
    }

}
